﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SqlRunner.uiStatus;
using SQLRunnerLib;
using SQLRunnerLib.Services;
using System.Text.RegularExpressions;
using SQLRunnerLib.Util;
using SQLServices.Log;

namespace SqlRunner
{
    public partial class frmEnvironmentDetails : Form
    {
        private SQLRunnerLib.Environment _environment;
        private bool IsConnAvailable = false;

        public frmEnvironmentDetails()
        {
            InitializeComponent();
            SetGroups();          
        }

        public frmEnvironmentDetails(SQLRunnerLib.Environment environment)
            : this()
        {
            _environment = environment;

            txtEnvironment.Text = environment.Name;
            cboServer.Text = environment.ServerName;
            cboAuthentication.DataSource = Enum.GetNames(typeof(AuthenticationType));
            cboAuthentication.SelectedItem = Enum.GetName(typeof(AuthenticationType), environment.Authentication);
            cboDatabase.Text = environment.DatabaseName;
            if (environment.Authentication == AuthenticationType.SQLServerAuthentication)
            {
                txtUsername.Text = environment.Username;
                txtPassword.Text = environment.Password;
                chkRemeberPassword.Checked = environment.SavePassword;
            }
            placeHoldersBindingSource.DataSource = environment.PlaceHolders;
        }

        private void cboAuthentication_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboAuthentication.Text != string.Empty)
            {
                if ((AuthenticationType)Enum.Parse(typeof(AuthenticationType), cboAuthentication.Text) == AuthenticationType.WindowsAuthentication)
                {
                    txtUsername.Text = string.Empty;
                    txtPassword.Text = string.Empty;
                    txtUsername.Enabled = false;
                    txtPassword.Enabled = false;
                    chkRemeberPassword.Enabled = false;
                    chkRemeberPassword.Checked = false;
                }
                else
                {
                    txtUsername.Enabled = true;
                    txtPassword.Enabled = true;
                    chkRemeberPassword.Enabled = true;
                }
            }

        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            //TODO: Validate that all values have been entered.
            _environment.Name = txtEnvironment.Text;
            _environment.ServerName = cboServer.Text;            
            _environment.Authentication = Enum<AuthenticationType>.Parse(cboAuthentication.Text);
            _environment.Username = txtUsername.Text;
            _environment.Password = txtPassword.Text;
            _environment.SavePassword = chkRemeberPassword.Checked;
            _environment.DatabaseName = cboDatabase.Text;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;   
                List<string> servers = ServiceContainer.SQLServerFinder.GetSQLServers();
                if (servers == null)
                {
                    MessageBox.Show("No SQL Servers were found.");
                    return;
                }
                frmServerSearch searchForm = new frmServerSearch(servers);
                DialogResult result = searchForm.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    if (!cboServer.Items.Contains(searchForm.Server))
                    {
                        cboServer.Items.Add(searchForm.Server);
                    }
                    if (cboServer.Text.Equals(searchForm.Server)) return;
                    cboServer.Text = searchForm.Server;
                    IsConnAvailable = false;
                    CheckFormStatus();
                }                
            }
            finally
            {
                Cursor = Cursors.Default;   
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            IsConnAvailable = false;
            setComment("Connecting to [{0}] SQL Server, please wait ...", cboServer.Text);
            try
            {
                ConnectToSql(cboDatabase,
                    cboServer.Text, txtUsername.Text, txtPassword.Text, (AuthenticationType)Enum.Parse(typeof(AuthenticationType), cboAuthentication.Text));
                IsConnAvailable = true;
                setComment("Connection was established to server [{0}], please select database", cboServer.Text);
            }
            catch (Exception exception)
            {
                Regex expression = new Regex(@"(\[(\w*\s*)*\])+");
                string msg = expression.Replace(exception.Message, "");
                ServiceContainer.Logger.LogMessage(
                    String.Format("Error openning connection: {0}", msg), MsgLevel.Error);
                MessageBox.Show(this, String.Format(
                    "The following error took place when connecting to the [{0}] SQL Server: \n\n{1}"
                    , cboServer.Text, msg), "SQL Runner - Error openning connection");
                setComment("Idle, please connect to SQL Server", "");
                
            }
            finally
            {
                Cursor = Cursors.Default;    
            }
            CheckFormStatus();
            
        }
               
        private void ConnectToSql( ComboBox comboBox, 
                                   string server,
                                   string userName, 
                                   string password, 
                                   AuthenticationType authenticationType)
        {
            bool trusted = (authenticationType == AuthenticationType.WindowsAuthentication);
            ServiceContainer.SQLConnection.OpenConnection(server, userName, password, trusted);
            comboBox.Items.Clear();
            comboBox.Items.AddRange(ServiceContainer.SQLConnection.ListOfDatabases().ToArray());          
        }

        private void setComment(string format, params object[] args)
        {
            ServiceContainer.Logger.LogMessage("setComment method was called");
            toolStripStatus.Text = String.Format(format, args);
        }        

    }
}
